package com.poker.service;

import com.poker.consts.Code;
import com.poker.entity.UserLog;
import com.poker.repository.UserLogRepository;
import com.poker.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserLogService {

    @Resource
    private UserLogRepository repository;

    /**
     * @param: [page, size];
     * @return: org.springframework.data.domain.Page<User>;
     * @Description: 不带条件分页查询;
     */
    public Page<UserLog> findUserLogNoCriteria(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "operateDate");

        return addProperty(repository.findAll(pageable));
    }

    /**
     * @param: [page, size, workOrder];
     * @return: org.springframework.data.domain.Page<WorkOrder>;
     * @Description: 带条件的分页查询;
     */
    public Page<UserLog> findUserLogCriteria(Integer page, Integer size, UserLog userLog) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "operateDate");

        return addProperty(repository.findAll((Specification<UserLog>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            if (Misc.isNotEmpty(userLog.getUserName()))
                list.add(criteriaBuilder.equal(root.get("userName").as(String.class), userLog.getUserName()));

            if (Misc.isNotEmpty(userLog.getOperateName()))
                list.add(criteriaBuilder.equal(root.get("operateName").as(String.class), userLog.getOperateName()));

            Predicate[] predicateArray = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(predicateArray));
        }, pageable));
    }

    private Page<UserLog> addProperty(Page<UserLog> pages) {
        for (UserLog log: pages) { addProperty(log); }

        return pages;
    }

    private UserLog addProperty(UserLog log) {
        log.setOperateAspectName(Code.OperateAspect.get(log.getOperateAspect()));

        return log;
    }
}
